//
//  DXMessageViewController.swift
//  nineteenfloor
//
//  Created by 大郗 on 16/3/6.
//  Copyright © 2016年 大郗. All rights reserved.
//

import UIKit

class DXMessageViewController: UIViewController {
	// 频道的ScrollView
	@IBOutlet weak var channelScrollView: UIScrollView!
	// 频道item的父控件
	@IBOutlet weak var newsContentView: UICollectionView!

	// 频道的模型数组
	var channels: NSArray?
	// ChannelLabel控件的数组
	var channelLabels: NSMutableArray?
	// 当前选中的ChannelLabel标签
	var currentSelectIndex: NSInteger?

	override func viewDidLoad() {
		super.viewDidLoad()
		view.backgroundColor = UIColor.redColor()
		self.automaticallyAdjustsScrollViewInsets = false
		// 创建频道标签
		self.setupChannelLabels()
	}

	func setupChannelLabels() {
		// 1.获取频道的数组
		self.channels = DXChannel.channels()

		// 初始化装ChannelLabel控件的数组
		self.channelLabels = NSMutableArray()

		// 2.根据模型的个数,创建对应个数的频道标签
		let channelLabelW : CGFloat = 80;
		let channelLabelY : CGFloat = 0;
		let channelLabelH : CGFloat = self.channelScrollView.bounds.size.height;
		var channelLabelX : CGFloat = 0;
		for index in 0..<self.channels!.count {
			// 创建ChannelLabel
			let channelLabel = DXChannelLabel()

			if (index == 0) {
				channelLabel.textColor = UIColor(red: 168 / 255, green: 197 / 255, blue: 3 / 255, alpha: 1)
			}

			// 将新建立的ChannelLabel加入到数组中
			self.channelLabels?.addObject(channelLabel)

			// channelLabel.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];

			// 2.2 设置尺寸
			channelLabelX = CGFloat(index) * channelLabelW;
			channelLabel.frame = CGRectMake(channelLabelX, channelLabelY, channelLabelW, channelLabelH) ;

			// 2.3 将其添加到父控件
			self.channelScrollView .addSubview(channelLabel)

			// 2.4 设置文字
			channelLabel.text = (self.channels![index] as! DXChannel).tname

			channelLabel.tag = index;

			// 2.5 给每一个Channel添加手势事件
			channelLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "channelClick:"))

			// 2.6 让channelLabel开启用户交互
			channelLabel.userInteractionEnabled = true
		}

		// 3.设置channelScrollView的滚动范围
		self.channelScrollView.contentSize = CGSizeMake(channelLabelW * CGFloat(self.channels!.count), 0)
        
	}
}
	// pragma mark - UICollectionView的代理方法
	extension DXMessageViewController: UICollectionViewDataSource, UICollectionViewDelegate {
        
		func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
			return self.channels!.count
		}

		func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
			// 1.从Storyboard加载
			var cell = collectionView .dequeueReusableCellWithReuseIdentifier("NewsContentItem", forIndexPath: indexPath)

			// 2.给我们自定义的cell,传值
			var currentChannel = self.channels![indexPath.item]

			if (self.newsContentView.tag != -1) { // 手工滚动
				cell.URLString = currentChannel.URLString;
			} else { // 点击了ChannelLabel
				if (self.currentSelectIndex == indexPath.item) {
					cell.URLString = currentChannel.URLString;
				} else {
					cell.URLString = nil;
				}
			}

			return cell
		}

		// pragma mark - 上下联动相关代码
		func channelClick(recognizer: UITapGestureRecognizer) {
			var channelLabel = ChannelLabel(recognizer.view)
			var index = channelLabel.tag;
			self.currentSelectIndex = index;
			// 1.设置newsContentView为-1
			self.newsContentView.tag = -1;
			// 2.让下面的CollectionView滚动
			self.newsContentView.setContentOffset(CGPointMake(index * self.newsContentView.bounds.size.width, 0), animated: true) ;
		}

		/**
		 正在滚动

		 左右两边的标签加载起是1
		 */
		func scrollViewDidScroll(scrollView: UIScrollView) {

			if (self.newsContentView.tag == -1) {
				return
			}

			// 0.滚动的位置
			let value = scrollView.contentOffset.x / scrollView.bounds.size.width;

			if (value < 0 || value > CGFloat( self.channelLabels!.count - 1)) {

				return
			}

			// 1.左边的索引
			let leftIndex = Int(scrollView.contentOffset.x) / Int(scrollView.bounds.size.width)

			// 2.右边的索引
			let rightIndex = leftIndex + 1

			// 3.获取右边的缩放比率
			let rightScale = value - CGFloat( leftIndex)

			// 4.获取左边的缩放比率
			let leftScale = 1 - rightScale

			// 5.取出左右两边的ChannelLabel,给其设置缩放
			var leftChannelLabel = self.channelLabels![leftIndex]
			leftChannelLabel.scale = leftScale

			// 6.判断一下,以免越界
			if (rightIndex < self.channelLabels!.count) {
				var rightChannelLabel = self.channelLabels![rightIndex]
				rightChannelLabel.scale = rightScale
			}
		}

		func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {

			self.scrollViewDidEndScrollingAnimation(scrollView)
		}

		func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {

			self.newsContentView.tag = 0

			// 1.自己计算当前滚动到哪一页了
			var currentPage = Int(scrollView.contentOffset.x) / Int(scrollView.bounds.size.width)

			// 2.记录当前滚动到哪个地方来了
			self.currentSelectIndex = currentPage;
			// 3.获取当前选中的ChannelLabel
			var selectedChannelLabel = self.channelLabels![currentPage]

			// 4.让选中的ChannelLabel居中
			var needScrollViewX = selectedChannelLabel.center.x - self.channelScrollView.bounds.size.width * 0.5

			// 最小滚动的距离
			if (needScrollViewX < 0) {
				needScrollViewX = 0
			}
			// 最大允许滚动的长度
			var maxScrollViewX = self.channelScrollView.contentSize.width - self.channelScrollView.bounds.size.width;
			if (needScrollViewX > maxScrollViewX) {
				needScrollViewX = maxScrollViewX
			}

			self.channelScrollView.setContentOffset(CGPointMake(needScrollViewX, 0), animated: true)

			for channelLabel in self.channelLabels! {
				if (channelLabel.tag == self.currentSelectIndex) {
					channelLabel.scale = 1.0;
				} else {
					channelLabel.scale = 0.0;
				}
			}
		}
	}

